#import "FlutterFnSdkPlugin.h"
#import "FnSdkHeader.h"
#import "FlutterEventAction.h"

@interface FlutterFnSdkPlugin ()<FlutterStreamHandler>

@property (copy, nonatomic) FlutterEventSink eventSink;
/**环境  YES生产环境  NO开发环境*/
@property (assign, nonatomic) bool isRelease;
//appid
@property (strong, nonatomic) NSString *appId;

@property (strong, nonatomic) FnSplashAd *splashAd;

@property (strong, nonatomic) FnInsertAd *insertAd;

@property (strong, nonatomic) FnRewardVideoAd *rewardVideoAd;

@property (strong, nonatomic) FnScreenVideoAd *screenVideoAd;

@end

@implementation FlutterFnSdkPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterFnSdkPlugin* instance = [[FlutterFnSdkPlugin alloc] init];

  
    FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"flutter_fn_sdk"
            binaryMessenger:[registrar messenger]];
    [registrar addMethodCallDelegate:instance channel:channel];
    
    
    FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"flutter_fn_sdk_event"
                                                                  binaryMessenger:[registrar messenger]];
    [eventChannel setStreamHandler:instance];
    
}



- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([call.method isEqualToString:@"initAd"]){
      //初始化
      NSString *appId = call.arguments[@"appId"];
      bool test = [call.arguments[@"test"] boolValue];
      bool debug = [call.arguments[@"debug"] boolValue];
      self.isRelease = !test;
      self.appId = appId;
      // 初始化FNSDK 调用顺序不能写错！！！
      [FNADManagers sharefnADManager].isRelease = self.isRelease;
      [[FNADManagers sharefnADManager] initWithFNAppID: self.appId];
      result([NSNumber numberWithBool:YES]);
  }else if ([call.method isEqualToString:@"showSplashAd"]){
      NSString *posId = call.arguments[@"posId"];
      //显示开屏
      [self showshowSplashAdWithAdsId: posId];
      result([NSNumber numberWithBool:YES]);
  }else if ([call.method isEqualToString:@"showScreenVideoAd"]){
      //全屏插屏广告
      NSString *posId = call.arguments[@"posId"];
      [self showScreenVideoAdWithAdsId:posId];
  }else if ([call.method isEqualToString:@"closeScreenVideoAd"]){
      //关闭全屏插屏广告
      NSString *posId = call.arguments[@"posId"];
      [self closeScreenVideoAd:posId];
      result([NSNumber numberWithBool:YES]);
  }else if ([call.method isEqualToString:@"showInterstitialAd"]){
      //插屏广告
      NSString *posId = call.arguments[@"posId"];
      [self showInterstitialAdWithAdsId:posId];
      result([NSNumber numberWithBool:YES]);
  }else if ([call.method isEqualToString:@"showRewardVideoAd"]){
      // 激励广告
      [self showRewardVideoWithArguments:call.arguments];
      result([NSNumber numberWithBool:YES]);
  }else {
    result(FlutterMethodNotImplemented);
  }
}


#pragma mark ----- FlutterStreamHandler
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)events{
    self.eventSink = events;
    return nil;
}

- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{
    
    return nil;
}
#pragma mark ----- 广告
//开屏广告
-(void)showshowSplashAdWithAdsId:(NSString *)adsId{
    FnSplashAd *splashAd = [FnSplashAd loadAdWithAppId:self.appId adsId:adsId isRelease:self.isRelease];
    self.splashAd = splashAd;
    __weak typeof(self) weakSelf = self;
    splashAd.onError = ^(NSError * _Nonnull error) {
        [weakSelf errorEventSinkWithAdId:adsId error:error];
        weakSelf.splashAd = nil;
    };
    splashAd.onClosed = ^{
        [weakSelf eventSinkWithAction:onAdClosed adId:adsId];
        weakSelf.splashAd = nil;
    };
    splashAd.onShow = ^{
        [weakSelf eventSinkWithAction:onAdExposure adId:adsId];
    };
    splashAd.onClicked = ^{
        [weakSelf eventSinkWithAction:onAdClicked adId:adsId];
    };
    
}

//显示插屏广告
- (void)showInterstitialAdWithAdsId:(NSString *)adsId{
    self.insertAd = [FnInsertAd loadAdWithAppId:self.appId adsId:adsId isRelease:self.isRelease];
    __weak typeof(self) weakSelf = self;
    self.insertAd.onError = ^(NSError * _Nonnull error) {
        [weakSelf errorEventSinkWithAdId:adsId error:error];
        weakSelf.insertAd = nil;
    };
    
    self.insertAd.onClosed = ^{
        [weakSelf eventSinkWithAction:onAdClosed adId:adsId];
        weakSelf.insertAd = nil;
    };
    
    self.insertAd.onShow = ^{
        [weakSelf eventSinkWithAction:onAdExposure adId:adsId];
    };
    
    self.insertAd.onClicked = ^{
        [weakSelf eventSinkWithAction:onAdClicked adId:adsId];
    };
}

///全屏插屏广告
- (void)showScreenVideoAdWithAdsId:(NSString *)adsId{
    self.screenVideoAd = [FnScreenVideoAd loadAdWithAppId:self.appId adsId:adsId isRelease:self.isRelease];
    __weak typeof(self) weakSelf = self;
    self.screenVideoAd.onError = ^(NSError * _Nonnull error) {
        [weakSelf errorEventSinkWithAdId:adsId error:error];
        weakSelf.screenVideoAd = nil;
    };
    
    self.screenVideoAd.onClosed = ^{
        [weakSelf eventSinkWithAction:onAdClosed adId:adsId];
        weakSelf.screenVideoAd = nil;
    };
    
    self.screenVideoAd.onShow = ^{
        [weakSelf eventSinkWithAction:onAdExposure adId:adsId];
    };
    
    self.screenVideoAd.onClicked = ^{
        [weakSelf eventSinkWithAction:onAdClicked adId:adsId];
    };
}

/// 关闭全屏插屏广告
- (void)closeScreenVideoAd:(NSString *)adsId{
    
}

//显示激励视频
- (void)showRewardVideoWithArguments:(id)arguments{
    NSString *posId = arguments[@"posId"];
    NSString *customData = arguments[@"customData"];
    NSString *userId = arguments[@"userId"];
    if ([customData isKindOfClass:[NSNull class]] || customData == nil) {
        customData = @"";
    }
    if ([userId isKindOfClass:[NSNull class]] || userId == nil) {
        userId = @"";
    }
    
    self.rewardVideoAd = [FnRewardVideoAd loadAdWithAppId:self.appId
                                                    adsId:posId
                                                isRelease:self.isRelease
                                                   userId:userId
                                                extraInfo:customData];
    __weak typeof(self) weakSelf = self;
    self.rewardVideoAd.onError = ^(NSError * _Nonnull error) {
        [weakSelf errorEventSinkWithAdId:posId error:error];
        weakSelf.rewardVideoAd = nil;
    };
    
    self.rewardVideoAd.onClosed = ^{
        [weakSelf eventSinkWithAction:onAdClosed adId:posId];
        weakSelf.rewardVideoAd = nil;
    };
    
    self.rewardVideoAd.onLoad = ^{
        [weakSelf eventSinkWithAction:onAdLoaded adId:posId];
    };
    
    self.rewardVideoAd.onShow = ^{
        [weakSelf eventSinkWithAction:onAdExposure adId:posId];
    };
    
    self.rewardVideoAd.onClicked = ^{
        [weakSelf eventSinkWithAction:onAdClicked adId:posId];
    };
    
    self.rewardVideoAd.onReward = ^(NSString * _Nonnull orderId) {
        [weakSelf rewardEventSinkWithAdId:posId orderId:orderId userId:userId customData:customData];
    };
}

//普通事件回调flutter
- (void)eventSinkWithAction:(NSString *)action adId:(NSString *)adId{
    if (self.eventSink) {
        NSDictionary *result = @{@"action" : action, @"adId": adId};
        self.eventSink(result);
    }
}

//错误事件回调flutter
- (void)errorEventSinkWithAdId:(NSString *)adId error:(NSError *)error{
    if (self.eventSink) {
        NSDictionary *result = @{@"action" : onAdError,
                                 @"adId": adId,
                                 @"errCode" : [NSNumber numberWithInteger:error.code],
                                 @"errMsg" : [NSString stringWithFormat:@"%@",error.userInfo[@"NSLocalizedFailureReason"]]
        };
        self.eventSink(result);
    }
}

//达成奖励事件回调flutter
- (void)rewardEventSinkWithAdId:(NSString *)adId orderId:(NSString *)orderId userId:(NSString *)userId customData:(NSString *)customData{
    if (self.eventSink) {
        NSDictionary *result = @{@"action" : onAdReward,
                                 @"adId": adId,
                                 @"transId" : [NSString stringWithFormat:@"%@", orderId],
                                 @"customData" : customData,
                                 @"userId" : userId
        };
        self.eventSink(result);
    }
}

@end
